import matplotlib

matplotlib.use('Agg')
import os
from ..config import QC_FIG_CONFIG, DISTRIBUTION_STEP
import numpy as np

import matplotlib.pyplot as plt


def __set_rc():
    matplotlib.rcdefaults()
    matplotlib.style.use(QC_FIG_CONFIG['style'])
    matplotlib.rc('figure', figsize=[QC_FIG_CONFIG['fig_width'], QC_FIG_CONFIG['fig_height']],
                  dpi=QC_FIG_CONFIG['dpi'])
    matplotlib.rcParams['text.usetex'] = False
    matplotlib.rcParams['font.family'] = 'DejaVu Sans'


def __plot_distribution_rate(data, title, cell, outdir):
    output = os.path.join(outdir, '%s.%s.png' % (cell, title.replace(' ', '_').lower()))
    if os.path.exists(output): return output
    y1, y2, xticks = list(), list(), list()
    for info in data[::-1]:
        if info['rc_rate'] == info['bs_rate'] == 0: continue
        xticks.append(info['name'])
        y1.append(info['rc_rate'] * 100)
        y2.append(info['bs_rate'] * 100)
    x = np.arange(len(y1))
    __set_rc()
    fig = plt.figure()
    width = 0.4
    plt.title('%s:%s' % (cell, title), fontsize=15)
    plt.xlabel('Read Length', fontsize=10)
    plt.ylabel('Percentage(%)', fontsize=10)
    plt.bar(x - width / 2, height=y1, width=width, alpha=1, color='coral', label="Reads")
    plt.bar(x + width / 2, height=y2, width=width, alpha=1, color='darkturquoise', label='Bases')
    print(len(x), len(xticks))
    plt.xticks(ticks=x, labels=xticks, rotation=90)
    plt.legend()
    # plt.margins(0.2)
    plt.subplots_adjust(bottom=0.15)
    output = os.path.join(outdir, '%s.%s.png' % (cell, title.replace(' ', '_').lower()))
    fig.savefig(output)
    plt.close('all')
    return output


def __plot_distribution_count(data, title, cell, outdir):
    output = os.path.join(outdir, '%s.%s.png' % (cell, title.replace(' ', '_').lower()))
    if os.path.exists(output): return output
    y, xticks = list(), list()
    for info in data[::-1]:
        if info['reads_count'] == 0: continue
        xticks.append(info['name'])
        y.append(info['reads_count'])
    x = np.arange(len(y))
    __set_rc()
    fig = plt.figure()
    width = 0.4
    plt.title('%s:%s' % (cell, title), fontsize=15)
    plt.xlabel('Read Length', fontsize=10)
    plt.ylabel('Count', fontsize=10)
    plt.bar(x, height=y, width=width, alpha=1, color='coral', label="Reads")
    plt.xticks(ticks=x, labels=xticks, rotation=90)
    plt.legend()
    plt.subplots_adjust(bottom=0.15)
    fig.savefig(output)
    plt.close('all')
    return output


def __plot_volume(data, title, outdir):
    output = os.path.join(outdir, '%s.png' % (title.replace(' ', '_').lower()))
    if os.path.exists(output): return output
    y1, y2, xticks = list(), list(), list()
    for cell in data['cells']:
        xticks.append(cell['cell'])
        y1.append(100 * cell['hq_read_num'] / data['meta']['total_reads'])
        y2.append(100 * cell['hq_base_num'] / data['meta']['total_bases'])
    x = np.arange(len(y1))
    __set_rc()
    fig = plt.figure()
    width = 0.4
    plt.title(title, fontsize=15)
    plt.xlabel('FlowCell', fontsize=10)
    plt.ylabel('Percentage(%)', fontsize=10)
    plt.bar(x - width / 2, height=y1, width=width, alpha=1, color='coral', label="Reads")
    plt.bar(x + width / 2, height=y2, width=width, alpha=1, color='darkturquoise', label='Bases')
    plt.xticks(ticks=x, labels=xticks, rotation=90)
    plt.legend()
    # plt.margins(0.2)
    plt.subplots_adjust(bottom=0.4)
    fig.savefig(output)
    plt.close('all')
    return output


def run_plot(volume_stat, distribution_stat, outdir):
    distribution_cumulative_percent_images = list()
    distribution_interval_percent_images = list()
    distribution_interval_count_images = list()
    for info in distribution_stat:
        distribution_cumulative_percent_images.append(
            __plot_distribution_rate(info['cumulative'], 'Cumulative Distribution of Read Length Percent', info['cell'], outdir)
        )
        distribution_interval_percent_images.append(
            __plot_distribution_rate(info['interval'], 'Interval Distribution of Read Length Percent', info['cell'], outdir)
        )
        distribution_interval_count_images.append(
            __plot_distribution_count(info['interval'], 'Interval Distribution of Read Length Count', info['cell'], outdir)
        )
    volume_image = __plot_volume(volume_stat, 'Data Volume', outdir)
    return distribution_cumulative_percent_images, distribution_interval_percent_images, distribution_interval_count_images, volume_image
